/*
 *Create By：Z.B
 *@DATE 2019/3/19 11:54
 *@EMAIL: 2545375@qq.com
 */
'use strict';

const Service = require('egg').Service;

class UserAccessService extends Service {

  /**
   * 登陆
   * @param payload
   * @returns {Promise<{token: *}>}
   */
  async login(payload) {
    const {ctx, service} = this;
    const user = await service.user.findByAccount(payload.account);
    if (!user) {
      ctx.throw(404, 'user not found');
    }
    let verifyPsw = await ctx.compare(payload.password, user.password);
    if (!verifyPsw) {
      ctx.throw(404, '密码错误');
    }
    return {token: await service.actionToken.apply(user._id)};
  }

  /**
   * 登出
   * @returns {Promise<void>}
   */
  async logout(){

  }

  /**
   * 当前用户
   * @returns {Promise<*>}
   */
  async current(){
    const {ctx, service } = this;
    const _id = ctx.state.user.data._id;
    const user = await service.user.find(_id);
    if(!user){
      ctx.throw(404,'用户没有找到,该用户不存在');
    }
    user.password = 'How old are you? 18';
    return user;
  }

  /**
   * 修改信息
   * @param values
   * @returns {Promise<*>}
   */
  async resetSelf(values){
    const {ctx, service} = this;
    //获取当前用户
    const _id = ctx.state.user.data._id;
    const user = await service.user.find(_id);
    if (!user) {
      ctx.throw(404, '用户不存在');
    }
    return service.user.findByIdAndUpdate(_id, values);
  }

  /**
   * 修改密码
   * @param values
   * @returns {Promise<*>}
   */
  async resetPsw(values){
    const {ctx, service} = this;
    const _id = ctx.state.user.data._id;
    const user = await service.user.find(_id);
    if(!user){
      ctx.throw(404,`用户id: ${_id}的用户未找到`);
    }
    let verifyPws = await ctx.compare(values.password,user.password);
    if(!verifyPws) {
      ctx.throw(404, '输入密码错误,无法修改');
    }else{
      values.password = await ctx.genHash(values.password);
      return service.user.findByIdAndUpdate(_id,values);
    }
  }
}

module.exports = UserAccessService;

